/*
 *  $Id: Avatar.cs 1217 2010-11-27 10:48:54Z thenn.erannor $
 *	This file is a part of Ragima CCG.
 *	(C) 2008-2010 Ragima development group.
 *
 *	Licensed under the terms of the GNU GPL License version 2.
 *
 */

using System.IO;

using Nereal.Serialization;

namespace Ragima.Events {
    [TypeId("avatar")]
    public class Avatar : DirectConnectEvent {
        [Serialize, XmlName("request")]
        private bool _request;
        [Serialize, XmlName("name")]
        private string _name;
        [Serialize, XmlName("avatar"), XmlStoreAsElement]
        private byte[] _data;

        public Avatar() {
            _request = true;
        }
        public Avatar(bool request, string name) {
            _request = request;
            _name = name;
            if (!_request)
                ReadAvatar();
        }

        private FilePath FullName {
            get { return Paths.Avatars[_name]; }
        }

        protected override void ExecuteInner(DirectConnectScene scene) {
            if (_request) {
                scene.Log.Add(Resources.DirectConnect.AvatarSend);
                scene.Mode.SendEvent(new Avatar(false, _name));
            } else {
                scene.Log.Add(Resources.DirectConnect.AvatarReceive);
                WriteAvatar();
                scene.CheckDeckRequest();
            }
        }

        private void ReadAvatar() {
            var name = FullName;
            _data = name.Exists ? File.ReadAllBytes(name) : null;
        }

        private void WriteAvatar() {
            if (_data != null)
                File.WriteAllBytes(FullName, _data);
        }
    }
}
